// anxin-medical/src/utils/request.ts
import axios from 'axios'
import router from '../router/index'
import { useAppStore } from '../stores/appStore'
import { ElMessage } from 'element-plus'

// 创建axios实例（不依赖store）
const service = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || '/api', // 使用环境变量配置
  timeout: 10000,
  withCredentials: true
})

// 请求拦截器 - 确保能获取到最新token
service.interceptors.request.use(config => {
  // 直接从localStorage获取token（单一数据源）
  const token = localStorage.getItem('token')
  if (token) {
    config.headers = config.headers || {}
    config.headers['Authorization'] = 'Bearer ' + token
  }
  return config
}, error => {
  return Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use(
  response => {
    // 处理正常响应
    if (response.data.code === 401 ||(response.data.code === 500 && response.data.msg?.includes('登录已过期，请重新登录'))) {
      localStorage.removeItem('token')
      const currentPath = router.currentRoute.value.path
      if (currentPath.startsWith('/admin')) {
        useAppStore().logout(false, router)
        router.push('/admin/login')
      } else {
        useAppStore().logout(true, router)
      }
    } else if (response.data.code === 500) {
      ElMessage.error(response.data.msg)
    }
    return response.data
  },
  error => {
    console.log(error)
    // 统一错误处理
    const status = error.response?.status
    let message = error.message
    
    if (status === 401 || (status === 500 && error.response?.data?.msg?.includes('登录已过期，请重新登录'))) {
      message = '登录已过期，请重新登录'
      localStorage.removeItem('token')
      useAppStore().logout(true, router)
      const currentPath = router.currentRoute.value.path
      if (currentPath.startsWith('/admin')) {
        router.push('/admin/login')
      } else {
        
      }
    } else if (status === 403) {
      message = '无权限访问此资源'
    } else if (status === 500) {
      const msg = error.response?.data?.msg
      if (
        msg?.includes('登录已过期') ||
        msg?.includes('未登录')
      ) {
        message = msg || '登录已过期，请重新登录'
        localStorage.removeItem('token')
        useAppStore().logout(true, router)
        const currentPath = router.currentRoute.value.path
        if (currentPath.startsWith('/admin')) {
          router.push('/admin/login')
        } else {
          // window.dispatchEvent(new CustomEvent('show-login-modal')) // 由logout统一处理
        }
      } else {
        message = '服务器内部错误'
      }
    }
    
    console.error('API Error:', error.config?.url, error.response?.data)
    return Promise.reject({ message, status, data: error.response?.data })
  }
)

/**
 * 通用下载文件方法，自动解析content-disposition文件名
 * @param res axios响应对象
 * @param defaultFileName 默认文件名
 */
export function downloadBlobFile(res: any, defaultFileName = 'download.xlsx') {
  let blob = res.data instanceof Blob ? res.data : new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
  let fileName = defaultFileName
  try {
    const disposition = res.headers && (res.headers['content-disposition'] || res.headers['Content-Disposition'])
    if (disposition) {
      const match = disposition.match(/filename=([^;]+)/)
      if (match && match[1]) {
        fileName = decodeURIComponent(match[1].replace(/['"]/g, ''))
      }
    }
  } catch (e) {}
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = fileName
  a.click()
  URL.revokeObjectURL(url)
}

export default service